var express = require('express');
var router = express.Router();
var qs = require('querystring');
var myUtil = require('../utils/myUtil.js');
var dataChecker = require('../utils/dataChecker.js');
var dbUtil = require("../utils/dbUtil.js");

router.post('/', function(req, res) {
	var body = '';

	req.on('data', function(data) {
		body += data;
	});

	req.on('end', function() {
		var json = parseInput(body);

		if (!json.data) {
			res.send(JSON.stringify(json));
			return;
		}

		dbUtil.insertDevice(req.db, json.data, function(isOk, errMsg) {
			var result;
			if (isOk) {
				result = myUtil.resJsonOk(null);
			} else {
				result = myUtil.resJsonErr(errMsg);
			}
			res.send(JSON.stringify(result));
		});
	});
});

var template = {
	"deviceUuid": "xxxx",
	"model": "u8860",
	"imei": "1234"
};

function parseInput(data) {
	console.log(data);
	var json = myUtil.str2Json(data);
	if (!json) {
		return myUtil.resJsonErr("canot parse to json");
	}

	var checkResult = dataChecker.check(template, json);
	if (checkResult.isOk === false) {
		return myUtil.resJsonErr(checkResult.msg);
	}

	return myUtil.resJsonOk(json);
}

module.exports = router;